import { LOGIN_STATUS, LOGIN_BUSIN_STATUS } from "@/config/cache.js";
import { getUserInfo, getCurlOauth, getOpenidByCode } from "@/api/user";
import saveUserInfoToLocation from "@/composables/saveUserInfoToLocation";
import { toLogin } from "@/libs/login.js";
import { useTokenStore } from "@/store/index";
import { isWeixin, Tips } from "@/utils/index";
import Cache from "@/utils/cache";
let business_id = Cache.get("business_id");
async function setTokenHandler() {
  const token = uni.getStorageSync(LOGIN_STATUS);

  // #ifdef H5
  var url = window.location.href;
  var theRequest: Record<string, string> = {};
  if (url.indexOf("?") != -1) {
    var str = url.substr(url.indexOf("?") + 1);
    var strs = str.split("&");
    for (var i = 0; i < strs.length; i++) {
      theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
    }
  }

  if (theRequest.code) {
    // 存在code时，调用接口获取token
    // 使用code和state调用接口获取普通用户的token
    console.log("theRequest", theRequest);

    let res = await getOpenidByCode({
      code: theRequest.code,
      state: theRequest.state,
    });
    let { data, code, info } = res;
    let token = data.token.token;
    const tokenStore = useTokenStore();
    await tokenStore.setToken(token);
    if (code != 1)
      return Tips({
        title: info,
      });
    // 不是通过分享进入的，判断是否存在busin_token：不存在跳转登录页;存在获取用户信息并跳转首页
    if (!business_id) {
      if (!uni.getStorageSync(LOGIN_BUSIN_STATUS)) {
        toLogin();
      } else {
        getUserInfoHandler();
      }
    } else {
      // 分享进来授权公众号后直接跳转首页
      uni.switchTab({
        url: "/pages/tabbar/home",
      });
    }

    return;
  }
  if (!token) {
    //没有code 且没有token 时，获取跳转链接让用户授权公众号登录获取code
    getCurlOauthHandler();
    return;
  }
  // 没有code但是有token无需静默授权,根据情况跳转首页或者登录页
  if (business_id) {
    // 分享进来的情况直接跳转首页
    await getUserInfoHandler(); //判断授权token是否过期
    return;
  } else {
    // 不是通过分享进入的，判断是否存在busin_token：不存在跳转登录页;存在获取用户信息并跳转首页

    if (!uni.getStorageSync(LOGIN_BUSIN_STATUS)) {
      toLogin();
    } else {
      getUserInfoHandler();
    }
  }

  // #endif
}
function getUserInfoHandler() {
  // 缓存用户信息
  getUserInfo().then((res: any) => {
    saveUserInfoToLocation(res.data.business);
    uni.switchTab({
      url: "/pages/tabbar/home",
    });
  });
}
// 获取公众号授权链接并跳转
async function getCurlOauthHandler() {
  let redirect_uri = `https://bjp.yjgold.cn`;
  if (business_id) {
    redirect_uri += `?business_id=${business_id}`;
  }
  if (Cache.get("urltype")) {
    redirect_uri += `&urltype=${Cache.get("urltype")}`;
  }
  let params = { mode: 0, source: redirect_uri };
  let res = await getCurlOauth(params);
  let { auth_url, state } = res.data;
  window.location = auth_url;
}
export default setTokenHandler;
